package com.niit.musicserve.Intercepoter;

import com.niit.musicserve.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
	
	@Autowired
	private JwtUtil jwtUtil;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		
		// 获取请求头中的token
		String token = request.getHeader("Authorization");
		
		// 如果没有token，尝试从请求参数中获取
		if (token == null || token.isEmpty()) {
			token = request.getParameter("token");
		}
		
		// 如果仍然没有token，尝试从Bearer token中获取
		if (token != null && token.startsWith("Bearer ")) {
			token = token.substring(7);
		}
		
		// 没有token即未登录获取token，则返回未认证错误
		if (token == null || token.isEmpty()) {
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write("{\"code\":\"0\",\"msg\":\"未提供认证信息\"}");
			return false;
		}
		
		// 验证token是否有效
		if (!jwtUtil.validateToken(token)) {
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write("{\"code\":\"0\",\"msg\":\"认证信息无效或已过期\"}");
			return false;
		}
		
		// 解析token中的信息
		Claims claims = jwtUtil.getClaimsFromToken(token);
		if (claims != null) {
			request.setAttribute("claims", claims);
		}
		
		return true;
	}
}
